#include "util.h"
#include "slp.h"
#include "prog1.h"
#include "interp.h"
#include <stdio.h>

int maxargs(A_stm stm); // get the maximum number argument of any print 
						// statement within any subexpression of 'stm'

int maxargs_helper(A_exp exp); // get the maximum nubmer argument of any
							   // print statement within 'exp'

int main() {
	A_stm stm = prog();
	printf("maxargs(prog) is %d\n", maxargs(stm));
	interpStm(stm);
	return 0;	
}

int maxargs(A_stm stm) {
	// if 'stm' is CompoundStm, then return max(maxargs(stm.stm1), maxargs
	// (stm.stm2))
 	// if 'stm' is AssignStm, then return maxargs_helper(stm.exp);
	// if 'stm' is PrintStm, we should find the max value among
    // the length of stm.explist and maxargs_helper of each exp

	if(stm->kind == A_compoundStm) {
		int res1, res2;
		printf("compoundStm!\n");
		res1 = maxargs(stm->u.compound.stm1);
		res2 = maxargs(stm->u.compound.stm2);
		return res1 > res2 ? res1 :res2;	
	}

	if(stm->kind == A_assignStm) {
		printf("assignStm!\n");
		return maxargs_helper(stm->u.assign.exp);
	}
	
	int explist_length = 0;
 	int maxargs_exp; // record max result of maxargs_helper(exp)
	int res;
	A_expList p = stm->u.print.exps;
	
	printf("printStm!\n");
	while(p->kind == A_pairExpList) {
		++explist_length;
 		res = maxargs_helper(p->u.pair.head);
		maxargs_exp = res > maxargs_exp ? res : maxargs_exp;
		p = p->u.pair.tail;	
	}

	// solve the lastExpList
	++explist_length;
	res = maxargs_helper(p->u.last);
	maxargs_exp = res > maxargs_exp ? res : maxargs_exp;
	return maxargs_exp > explist_length ? maxargs_exp : explist_length;
}
int maxargs_helper(A_exp exp) {
	// if the kind of 'exp' isn't EseqExp, then return 0;
	// else return max(maxargs(exp.stm), maxargs_helper(exp.exp))

	if(exp->kind != A_eseqExp) {
		printf("non_eseqExp!\n");
		return 0;
	}
	int ret1, ret2;
	
	printf("eseqExp!\n");
	ret1 = maxargs(exp->u.eseq.stm);
    ret2 = maxargs_helper(exp->u.eseq.exp);
    return ret1 > ret2 ? ret1 : ret2;
}
